<template>
  <div class="add has-foot-pb">
    <Cell
      title="市场名称"
      required
      v-model="formData.marketName"
      divider
      :right="false"
      :isInput="true"
      input-align="right"
      placeholder="输入市场名称"
    />

    <FieldSelect
      v-model="formData.provinceId"
      title="省份"
      required
      :url="`/app/v1/mdmService/provinces`"
      label-name="name"
      value-name="id"
      method="get"
      clear
      @change="onChangeProvince"
    />
    <FieldSelect
      v-model="formData.cityId"
      title="城市"
      required
      :url="`/app/v1/mdmService/getByParentId/${formData.provinceId}`"
      label-name="name"
      value-name="id"
      method="get"
      :params="{ type: 1 }"
      :parentId="formData.provinceId"
      clear
      mustPid
      @change="onChangeCity"
    />
    <!-- query: { parentId: formData.provinceId }, -->

    <FieldSelect
      v-model="formData.districtId"
      title="区/县"
      :url="`/app/v1/mdmService/getByParentId/${formData.cityId}`"
      label-name="name"
      value-name="id"
      method="get"
      :params="{ type: 1 }"
      :parentId="formData.cityId"
      clear
      mustPid
      @change="onChangeDistricts"
    />

    <FieldSelect
      v-model="formData.streetId"
      title="街道/乡镇"
      :url="`/app/v1/mdmService/getByParentId/${formData.districtId}`"
      label-name="name"
      value-name="id"
      method="get"
      :params="{ type: 1 }"
      :parentId="formData.districtId"
      clear
      mustPid
      @change="onChangeStreet"
    />
    <FieldSelect
      v-model="formData.cityLevel"
      title="城市级别"
      required
      :url="`/data-dict/app/v2/dictionary/CITY_LEVEL`"
      label-name="dictName"
      value-name="dictCode"
      method="get"
      :params="dictParams"
      clear
    />
    <FieldSelect
      v-model="formData.agencyCode"
      v-model:label="formData.agencyName"
      title="所属办事处"
      required
      :url="`/app/v1/user/organization/agencies`"
      label-name="name"
      value-name="code"
      method="get"
      clear
    />
    <!-- :params="{ query: { isOffice: '1', status: 1 }, type: 0 }" -->
    <FieldSelect
      v-model="formData.marketNatrue"
      title="市场属性"
      required
      :url="`/data-dict/app/v2/dictionary/MARKET_NATURE`"
      label-name="dictName"
      value-name="dictCode"
      method="get"
      :params="dictParams"
      :includes="['A', 'B', 'C']"
      clear
    />
    <Cell title="是否有老商家" :custom="true" :right="false">
      <qmp-switch v-model="formData.isOldMerchant" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isOldMerchant ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>

    <Cell title="是否有遗留问题" :custom="true" :right="false">
      <qmp-switch v-model="formData.isLegacyProblem" :active-value="1" :inactive-value="0">
        <template #background>
          <span class="qmp-switch__background"> {{ formData.isLegacyProblem ? '是' : '否' }}</span>
        </template>
      </qmp-switch>
    </Cell>
    <Cell
      title="遗留问题"
      is-column
      custom
      divider
      :right="false"
      v-if="formData.isLegacyProblem === 1"
      :required="formData.isLegacyProblem === 1"
    >
      <qmp-field v-model="formData.legacyProblemMsg" type="textarea" placeholder="输入内容" class="ctm-text-area" />
    </Cell>

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onSubmit" :disabled="submiting">确认</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance, nextTick } from 'vue'
  import { useRouter, onBeforeRouteLeave } from 'vue-router'
  import Cell from '@/components/Cell/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  // import FieldArea from '@/components/FieldArea/index.vue'
  import { saveItem } from '@/apis/attractInvestment/blankMarket'
  import { isChange } from '@/utils'
  import GetKeyboardMixin from '@/utils/useKeyboard'

  interface anyObjectModle {
    // id: any
    dictParams: object
    formData: any
    submiting: boolean
    isEditBack: boolean
    [key: string]: any
  }

  const none: any[] = [undefined, null, '']

  export default {
    name: 'BlankMarketAdd',
    components: { Cell, FieldSelect },
    setup() {
      const { proxy }: any = getCurrentInstance()
      // const $route = useRoute()
      const $router = useRouter()

      const state = reactive<anyObjectModle>({
        // id: $route.query.id || '',
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        formData: {
          marketName: '',
          provinceCode: '',
          provinceName: '',
          provinceId: '',
          cityCode: '',
          cityName: '',
          cityId: '',
          districtCode: '',
          districtName: '',
          districtId: '',
          streetCode: '',
          streetName: '',
          streetId: '',
          agencyCode: '',
          agencyName: '',
          cityLevel: '',
          marketNatrue: '',
          isOldMerchant: 0,
          legacyProblemMsg: '',
          isLegacyProblem: 0
        },
        submiting: false,
        isEditBack: false // 是否是编辑成功后返回
      })
      state.keyboard = {
        show: false
      }
      state.keyboard = GetKeyboardMixin()

      const originalData = JSON.stringify(state.formData) // 原始数据 用于对比值是否发生变化
      // 省变更
      const onChangeProvince = (data: any) => {
        // console.log(data)

        state.formData.provinceCode = data.code
        state.formData.provinceName = data.name
        state.formData.provinceId = data.id

        state.formData.cityCode = ''
        state.formData.cityName = ''
        state.formData.cityId = ''
        state.formData.districtCode = ''
        state.formData.districtName = ''
        state.formData.districtId = ''
        state.formData.streetCode = ''
        state.formData.streetName = ''
        state.formData.streetId = ''

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }
      // 市变更
      const onChangeCity = (data: any) => {
        // console.log(data)
        state.formData.cityCode = data.code
        state.formData.cityName = data.name
        state.formData.cityId = data.id

        state.formData.districtCode = ''
        state.formData.districtName = ''
        state.formData.districtId = ''
        state.formData.streetCode = ''
        state.formData.streetName = ''
        state.formData.streetId = ''

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }
      // 区变更
      const onChangeDistricts = (data: any) => {
        // console.log(data)
        state.formData.districtCode = data.code
        state.formData.districtName = data.name
        state.formData.districtId = data.id

        state.formData.streetCode = ''
        state.formData.streetName = ''
        state.formData.streetId = ''

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }
      // 街道变更
      const onChangeStreet = (data: any) => {
        // console.log(data)
        state.formData.streetCode = data.code
        state.formData.streetName = data.name
        state.formData.streetId = data.id

        state.formData.cityLevel = data.cityLevel || '' // 城市级别
      }

      // 阻止返回
      onBeforeRouteLeave((to, from, next) => {
        if (state.isEditBack || isChange(state.formData, originalData)) next()
        else {
          proxy.$dialog
            .confirm({
              title: '当前编辑数据未保存，是否确认退出？',
              theme: 'round-button',
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              showCancelButton: true,
              closeOnPopstate: false
            })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
        }
      })

      const onSubmit = () => {
        console.log('onSubmit', state.formData)
        if (state.submiting) return
        const data = {
          // id: state.id,
          ...state.formData
        }

        if (none.includes(data.marketName)) {
          proxy.$toast('请输入市场名称')
          return
        }
        if (none.includes(data.provinceCode)) {
          proxy.$toast('请选择省份')
          return
        }

        if (none.includes(data.cityCode)) {
          proxy.$toast('请选择城市')
          return
        }

        if (none.includes(data.cityLevel)) {
          proxy.$toast('请选择城市级别')
          return
        }

        if (none.includes(data.agencyCode)) {
          proxy.$toast('请选择所属办事处')
          return
        }

        if (none.includes(data.marketNatrue)) {
          proxy.$toast('请选择市场属性')
          return
        }

        if (data.isLegacyProblem === 1 && none.includes(data.legacyProblemMsg)) {
          proxy.$toast('请输入遗留问题')
          return
        }
        state.submiting = true
        saveItem(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$toast('新增成功')
              proxy.$SimpleEvents.emit('refreshCustomerChangeItem')

              nextTick(() => {
                state.isEditBack = true
                $router.goBack()
              })
              state.submiting = false
            }
          })
          .catch((e: any) => {
            if (e) proxy.$toast(e)
            state.submiting = false
          })
      }

      return {
        ...toRefs(state),
        onSubmit,
        onChangeProvince,
        onChangeCity,
        onChangeDistricts,
        onChangeStreet
      }
    }
  }
</script>

<style lang="less" scoped>
  .add {
    margin-top: 8px;
  }
</style>
